package com.sky.service.impl;

import cn.mybatis.mp.core.sql.executor.chain.QueryChain;
import com.sky.entity.Books;
import com.sky.entity.Bookcategories;
import com.sky.mapper.BookcategoriesMapper;
import com.sky.mapper.BooksMapper;
import com.sky.service.PopularBooksStatisticsService;
import com.sky.vo.PopularBooksVO;
import com.sky.dto.PopularBooksQueryDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PopularBooksStatisticsServiceImpl implements PopularBooksStatisticsService {

    @Autowired
    private BooksMapper booksMapper;

    @Autowired
    private BookcategoriesMapper bookcategoriesMapper;

    @Override
    public PopularBooksVO getPopularBooks(PopularBooksQueryDTO queryDTO) {
        // 构建基础查询链
        QueryChain<Books> queryChain = QueryChain.of(booksMapper)
                .select(Books::getTitle, Books::getPopularityScore)
                .orderByDesc(Books::getPopularityScore)
                .limit(10);  // 限制返回前10条数据

        log.info("构建基础查询链: {}", queryChain);

        // 如果指定了分类，先查找该分类下的所有图书ID
        if (queryDTO.getCategory() != null && !queryDTO.getCategory().isEmpty()) {
            List<Integer> bookIds = QueryChain.of(bookcategoriesMapper)
                    .select(Bookcategories::getBookId)
                    .eq(Bookcategories::getCategoryId, queryDTO.getCategory())
                    .list()
                    .stream()
                    .map(Bookcategories::getBookId)
                    .collect(Collectors.toList());

            if (!bookIds.isEmpty()) {
                queryChain.in(Books::getBookId, bookIds);
            } else {
                // 如果该分类下没有图书，直接返回空结果
                return PopularBooksVO.builder()
                        .books(new ArrayList<>())
                        .borrowCount(new ArrayList<>())
                        .build();
            }
        }

        // 执行查询并获取前10条数据
        List<Books> books = queryChain.list();

        // 分别提取书名和热度分数（这里用热度分数代替借阅次数）
        List<String> bookNames = books.stream()
                .map(Books::getTitle)
                .collect(Collectors.toList());

        List<Integer> borrowCounts = books.stream()
                .map(book -> book.getPopularityScore().intValue())
                .collect(Collectors.toList());

        // 构建并返回结果
        return PopularBooksVO.builder()
                .books(bookNames)
                .borrowCount(borrowCounts)
                .build();
    }
} 